package cn.wang.service.impl;

import cn.wang.common.Exceptions.impl.LyException;
import cn.wang.common.enums.impl.ExceptionEnum;
import cn.wang.common.vo.PageResult;
import cn.wang.mapper.ISkuMapper;
import cn.wang.mapper.IStockMapper;
import cn.wang.mapper.ISupDetailMapper;
import cn.wang.mapper.ISpuMapper;
import cn.wang.pojo.*;
import cn.wang.service.IBrandService;
import cn.wang.service.ICategoryService;
import cn.wang.service.IGoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class GoodsService implements IGoodsService {
    @Autowired
    private ISpuMapper spuMapper;

    @Autowired
    private ISupDetailMapper supDetailMapper;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IBrandService brandService;
    @Autowired
    private ISkuMapper skuMapper;
    @Autowired
    private IStockMapper stockMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public PageResult<Spu> queryGoodsByPage(String key, Boolean saleable, Integer page, Integer rows) {
        // 分页
        PageHelper.startPage(page, rows);
        // 过滤
        Example example = new Example(Spu.class);
        // 根据过滤条件过滤
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria().andLike("title", "%" + key + "%");
        }
        // 根据是否上下架过滤
        if (saleable != null) {
            example.createCriteria().andEqualTo("saleable", saleable);
        }
        // 排序
        // 根据最后的修改时间进行排序
        example.setOrderByClause("last_update_time DESC");

        List<Spu> spus = spuMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(spus)) {
            throw new LyException(ExceptionEnum.GOOD_NOT_FOND);
        }
        // 获取分类名,品牌名称
        loadGategoryAndBrandName(spus);

        PageInfo<Spu> info = new PageInfo<>(spus);
        return new PageResult<Spu>(info.getTotal(), info.getPages(), info.getList());
    }

    /**
     * 保存商品
     *
     * @param spu
     */
    @Override
    @Transactional
    public void saveSpu(Spu spu) {
        // 保存spu表数据
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(spu.getCreateTime());
        spu.setSaleable(true);// 默认上架
        spu.setValid(true);
        int cont = spuMapper.insert(spu);
        if (cont != 1) {
            throw new LyException(ExceptionEnum.GOODS_SAVE_ERROR);
        }
        // 保存spuDetail表数据
        SpuDetail spuDetail = spu.getSpuDetail();
        spuDetail.setSpuId(spu.getId());
        cont = supDetailMapper.insert(spuDetail);
        // 保存sku表数据
        saveSku(spu);

        // 保存完后发送消息, 转发器通过配置文件配置
        amqpTemplate.convertAndSend("item.insert",spu.getId());
    }

    private void saveSku(Spu spu) {
        int cont;
        List<Sku> skus = spu.getSkus();
        for (Sku sku : skus) {
            sku.setSpuId(spu.getId());
            sku.setCreateTime(new Date(


            ));
            sku.setLastUpdateTime(sku.getCreateTime());
            sku.setEnable(true);
            cont = skuMapper.insert(sku);
            if (cont != 1) {
                throw new LyException(ExceptionEnum.GOODS_SAVE_ERROR);
            }
            // 保存stock表数据
            Stock stock = new Stock();
            stock.setStock(sku.getStock());
            stock.setSkuId(sku.getId());
            cont = stockMapper.insert(stock);
            if (cont != 1) {
                throw new LyException(ExceptionEnum.GOODS_SAVE_ERROR);
            }
        }
    }

    @Override
    public SpuDetail querySpuBySpuId(Long spuId) {
        SpuDetail spuDetail = supDetailMapper.selectByPrimaryKey(spuId);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.SUP_DETAIL_NOT_FIND);
        }
        return spuDetail;
    }

    /**
     * 根据spuid 获取所有的sku
     *
     * @param spuId
     * @return
     */
    @Override
    public List<Sku> querySkusBySpuId(Long spuId) {
        // 查询sku
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(skus)) {
            throw new LyException(ExceptionEnum.SKU_NOT_FIND);
        }
        // 根据skuId查询库存
        List<Stock> stocks = skus.stream().map(s -> stockMapper.selectByPrimaryKey(s.getId())).collect(Collectors.toList());
        // 生成sku和存春对应的map
        Map<Long, Integer> skuId2Storck = stocks.stream().collect(Collectors.toMap(Stock::getSkuId, Stock::getStock));
        // 为每一个sku设置库存
        skus.stream().forEach(s -> s.setStock(skuId2Storck.get(s.getId())));


        return skus;
    }

    /**
     * 更新商品信息
     *
     * @param spu
     */
    @Override
    @Transactional
    public void updateGoods(Spu spu) {
        if (spu.getId() == null) {
            throw new LyException(ExceptionEnum.SUP_NOT_NULL);
        }
        // 删除sku
        Sku s = new Sku();
        // 通过spu的id进行查询, 如果没有对应的sku就抛出异常
        s.setSpuId(spu.getId());
        List<Sku> skus = skuMapper.select(s);
        if (CollectionUtils.isEmpty(skus)) {
            throw new LyException(ExceptionEnum.SKU_NOT_FIND);
        }
        List<Long> ids = skus.stream().map(Sku::getId).collect(Collectors.toList());
        skuMapper.deleteByIdList(ids);
        // 删除stock
        stockMapper.deleteByIdList(ids);
        // 更新spu
        spu.setCreateTime(null);
        spu.setValid(null);
        spu.setSaleable(null);
        spu.setLastUpdateTime(new Date());
        int cont = spuMapper.updateByPrimaryKeySelective(spu);
        if (cont != 1) {
            throw new LyException(ExceptionEnum.GOODS_UPDATE_ERROR);
        }
        // 更新spuDetail
        cont = supDetailMapper.updateByPrimaryKeySelective(spu.getSpuDetail());
        if (cont != 1) {
            throw new LyException(ExceptionEnum.GOODS_UPDATE_ERROR);
        }
        // 添加sku
        // 添加stock
        saveSku(spu);
        // 修改完后发送消息, 转发器通过配置文件配置
        amqpTemplate.convertAndSend("item.update",spu.getId());
    }

    /**
     * 根据spuId查询spu
     *
     * @param spuId
     * @return
     */
    @Override
    public Spu queryGoodBySpuId(Long spuId) {
        // 查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        // 查询spuDetail
        spu.setSpuDetail(querySpuBySpuId(spuId));
        // 查询skus
        spu.setSkus(querySkusBySpuId(spuId));
        return spu;
    }

    // 加载分类名称和品牌名称
    private void loadGategoryAndBrandName(List<Spu> spus) {
        // 获取分类名称
        for (Spu spu : spus) {
            List<String> names = categoryService.queryByCids(spu.getCid1(), spu.getCid2(), spu.getCid3()).stream()
                    .map(Category::getName).collect(Collectors.toList());
            spu.setCname(StringUtils.join(names, "/")); // 将列表转成字符串, 以/作为分割
            // 获取品牌名称
            spu.setBname(brandService.queryBrandByBid(spu.getBrandId()).getName());
        }
    }


}
